﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Forms;
using VupSlashLauncher.Common;
using VupSlashLauncher.Model;
using VupSlashLauncher.View;

namespace VupSlashLauncher.ViewModel
{
    class MainViewModel : NotifyBase
    {
        System.Timers.Timer mytimer = new System.Timers.Timer(100) { AutoReset = true };
        public CommandBase CloseWindowCommand { get; set; }
        public CommandBase MinimizeWindowCommand { get; set; }
        public CommandBase AboutUSCommand { get; set; }
        public CommandBase StartGameCommand { get; set; }
        public CommandBase ViewChangeCommand { get; set; }
        public CommandBase SettingViewChangeCommand { get; set; }
        public CommandBase FileDownloadCommand { get; set; }
        public CommandBase GameWindowPositionResetCommand { get; set; }
        public CommandBase SetGameDirectoryCommand { get; set; }
        public CommandBase ThemeChangeCommand { get; set; }
        public CommandBase ChangeLocalVersionCommand { get; set; }
        public CommandBase AutoCheckLauncherUpdateCommand { get; set; }
        public ColorModel ColorModel { get; set; } = new ColorModel();
        public ShowModel ShowModel { get; set; } = new ShowModel();
        public IDownload IDownload { get; set; } = new IDownload();

        private FrameworkElement _maincontent;
        public FrameworkElement MainContent
        {
            get { return _maincontent; }
            set { _maincontent = value; this.DoNotify(); }
        }

        private FrameworkElement _settingmaincontent;
        public FrameworkElement SettingMainContent
        {
            get { return _settingmaincontent; }
            set { _settingmaincontent = value; this.DoNotify(); }
        }

        public MainViewModel()
        {
            InitContent();

            mytimer.Elapsed += new ElapsedEventHandler(RefreshContent);
            mytimer.Start();


            this.MinimizeWindowCommand = new CommandBase();
            this.MinimizeWindowCommand.DoExecute = new Action<object>((o) => { (o as System.Windows.Window).WindowState = WindowState.Minimized; });
            this.MinimizeWindowCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });
            this.MinimizeWindowCommand.CanExecuteChanged += null;

            this.AboutUSCommand = new CommandBase();
            this.AboutUSCommand.DoExecute = new Action<object>((o) => { System.Diagnostics.Process.Start(GlobalValues.BilibiliOfficialUrl); });
            this.AboutUSCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });

            this.StartGameCommand = new CommandBase();
            this.StartGameCommand.DoExecute = new Action<object>(DoStartGame);
            this.StartGameCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });

            this.ViewChangeCommand = new CommandBase();
            this.ViewChangeCommand.DoExecute = new Action<object>(DoViewChange);
            this.ViewChangeCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });

            this.SettingViewChangeCommand = new CommandBase();
            this.SettingViewChangeCommand.DoExecute = new Action<object>(DoSettingViewChange);
            this.SettingViewChangeCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });

            this.FileDownloadCommand = new CommandBase();
            this.FileDownloadCommand.DoExecute = new Action<object>(DoFileDownload);
            this.FileDownloadCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });

            this.GameWindowPositionResetCommand = new CommandBase();
            this.GameWindowPositionResetCommand.DoExecute = new Action<object>(DoGameWindowPositionReset);
            this.GameWindowPositionResetCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });

            this.SetGameDirectoryCommand = new CommandBase();
            this.SetGameDirectoryCommand.DoExecute = new Action<object>(DoSetGameDirectory);
            this.SetGameDirectoryCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });

            this.ThemeChangeCommand = new CommandBase();
            this.ThemeChangeCommand.DoExecute = new Action<object>(DoThemeChange);
            this.ThemeChangeCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });

            this.ChangeLocalVersionCommand = new CommandBase();
            this.ChangeLocalVersionCommand.DoExecute = new Action<object>(DoChangeLocalVersion);
            this.ChangeLocalVersionCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });

            this.AutoCheckLauncherUpdateCommand = new CommandBase();
            this.AutoCheckLauncherUpdateCommand.DoExecute = new Action<object>(DoAutoCheckLauncherUpdate);
            this.AutoCheckLauncherUpdateCommand.DoCanExecute = new Func<object, bool>((o) => { return true; });

        }

        private void DoStartGame(object o)
        {
            string GameWindow = INIOperation.INIGetStringValue(GlobalValues.GameDir + @".\config.ini", "General", "WindowPosition", "@Point(0 0)");
            string[] temp = GameWindow.Split(new char[] { '(', ' ', ')' });
            int GameWindowW = int.Parse(temp[1]);
            int GameWindowH = int.Parse(temp[2]);
            int AllScreenW = 0;
            int AllScreenH = 0;
            for (int i = 0; i < Screen.AllScreens.Length; i++)
            {
                AllScreenW += Screen.AllScreens[i].Bounds.Width;
                AllScreenH += Screen.AllScreens[i].Bounds.Height;
            }
            if ((GameWindowW > AllScreenW || GameWindowH > AllScreenH) && IMessageBox.Show("检测到你的游戏窗口已经溢出屏幕\n请进入设置重置游戏窗口位置获得最佳体验", "游戏窗口位置异常", "立即操作", "暂不需要"))
            {
                DoViewChange("SettingView");
                return;
            }
            try
            {
                Directory.SetCurrentDirectory(GlobalValues.GameDir);
                if (Process.Start(GlobalValues.GameExecuteFile) != null || Process.Start(GlobalValues.GameExecuteFileVup) != null)
                {
                    if (GlobalValues.CloseWhenStart) System.Windows.Application.Current.Shutdown();
                }

            }
            catch (Exception)
            {
                if (IMessageBox.Show("路径出错，无法打开游戏\n是否重新设置游戏路径？", "启动失败", "现在设置", "稍后再说", false))
                {
                    DoViewChange("SettingView");
                    DoSettingViewChange("SettingViewStartSettingView");
                }
            }
        }

        private void DoViewChange(object o)
        {
            Type type = Type.GetType("VupSlashLauncher.View." + o.ToString());
            ConstructorInfo cti = type.GetConstructor(System.Type.EmptyTypes);
            this.MainContent = (FrameworkElement)cti.Invoke(null);
            if (o.ToString() == "StartView") { ShowModel.IsButtonBarShow = false; ShowModel.IsBackButtonShow = false; ShowModel.TitleContent = null; }
            if (o.ToString() == "SettingView") { ShowModel.IsButtonBarShow = true; ShowModel.IsBackButtonShow = true; ShowModel.TitleContent = "设置"; }
            if (o.ToString() == "UpdateView") { ShowModel.IsButtonBarShow = false; ShowModel.IsBackButtonShow = true; ShowModel.TitleContent = "更新"; }
            if (o.ToString() == "GameInstallView") { ShowModel.IsButtonBarShow = false; ShowModel.IsBackButtonShow = false; ShowModel.TitleContent = "游戏安装"; }
            IFunc.LoadGameConfigFile();
            ShowModel.NameInGame = GlobalValues.NameInGame;
            ShowModel.GameHostIP = GlobalValues.GameHostIP;
            ShowModel.GameWindowW = GlobalValues.GameWindowW;
            ShowModel.GameWindowH = GlobalValues.GameWindowH;
        }

        public void GoToView(string view)
        {
            if ("VupSlashLauncher.View." + view != this.MainContent.ToString()) this.DoViewChange(view);
        }

        private void DoSettingViewChange(object o)
        {
            Type type = Type.GetType("VupSlashLauncher.View." + o.ToString());
            ConstructorInfo cti = type.GetConstructor(System.Type.EmptyTypes);
            this.SettingMainContent = (FrameworkElement)cti.Invoke(null);
            for (int i = 0; i < 5; i++) if (ShowModel.SVChildView[i] == true) ShowModel.SVChildView[i] = false;
            if (o.ToString() == "SettingViewGameSettingView") { ShowModel.SVChildView[0] = true; }
            else if (o.ToString() == "SettingViewStartSettingView") { ShowModel.SVChildView[1] = true; }
            else if (o.ToString() == "SettingViewThemeSettingView") { ShowModel.SVChildView[2] = true; }
            else if (o.ToString() == "SettingViewOtherSettingView") { ShowModel.SVChildView[3] = true; }
            else if (o.ToString() == "SettingViewAboutView") { ShowModel.SVChildView[4] = true; }
        }
        private async void DoFileDownload(object o)
        {
            string flag = o.ToString();
            switch (flag)
            {
                case "Pause":
                    {
                        if (IDownload.IsStart) IDownload.IsPause = !IDownload.IsPause;
                        else if (!GlobalValues.HaveNet) await Task.Run(IFunc.GetRefresh);
                        else if (GlobalValues.HaveNet)
                        {
                            if (IDownload.TaskTitle == "游戏补丁自动更新")
                            {
                                if (GlobalValues.LocalVersion == GlobalValues.LatestVersion)
                                {
                                    DoPatchUpdate();
                                }
                                else if (GlobalValues.LocalVersion != GlobalValues.VersionList[GlobalValues.VersionList.Length - 2][1])
                                {
                                    for (int i = 0; i < GlobalValues.VersionList.Length; i++)
                                    {
                                        if (GlobalValues.LocalVersion == GlobalValues.VersionList[GlobalValues.VersionList.Length - 1 - i][1])
                                        {
                                            DoPatchUpdate(i);
                                        }
                                    }
                                }
                            }
                            else if (IDownload.TaskTitle == "游戏主体文件安装")
                            {
                                DoMainInstall();
                            }
                        }
                    }
                    break;
                case "Cancel":
                    {
                        if (IDownload.TaskName == "游戏主体文件下载完成" || IDownload.TaskName == "正在解压资源" || IDownload.TaskName == "任务完成")
                            IMessageBox.Show("只能在下载阶段暂停操作", "任务提示", "好的");
                        else if (!IMessageBox.Show("真的要取消这个任务吗？", "任务取消", "手滑而已", "确定取消"))
                        {
                            IDownload.IsPause = true;
                            IDownload.IsStart = false;
                            IDownload.TaskOK = true;
                            await Task.Delay(800);
                            IDownload.TaskViewVisiability = "Collapsed";
                            try
                            {
                                if (File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.MainFile)) File.Delete(GlobalValues.GameDir + "\\" + GlobalValues.MainFile);
                                if (File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile)) File.Delete(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile);
                            }
                            catch { IMessageBox.Show("下载的文件仍保存在安装目录内，请手动处理", "文件占用", "好的"); }
                        }
                    }
                    break;
                case "MainGame":
                    {
                        if (!GlobalValues.HaveNet)
                        {
                            await Task.Run(IFunc.GetRefresh);
                            return;
                        }
                        else if (!IDownload.TaskOK)
                        {
                            IMessageBox.Show("已经有任务在进行了，请稍后再试", "下载提示", "好的");
                            return;
                        }
                        else if (File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.MainFile))
                        {
                            if (IMessageBox.Show("检测到上次未下载完的文件，是否继续上次更新？", "文件提示", "继续更新", "删除文件")) { }
                            else File.Delete(GlobalValues.GameDir + "\\" + GlobalValues.MainFile);
                        }
                        DoMainInstall();
                    }
                    break;
                case "LatestPatch":
                    {
                        if (!GlobalValues.HaveNet)
                        {
                            await Task.Run(IFunc.GetRefresh);
                        }
                        else if (!IDownload.TaskOK)
                        {
                            IMessageBox.Show("已经有任务在进行了，请稍后再试", "下载提示", "好的");
                        }
                        else if (GlobalValues.LocalVersion == GlobalValues.LatestVersion)
                        {
                            if (IMessageBox.Show("当前已经是最新版本了，仍要继续更新版本号为" + GlobalValues.LatestVersion + "的补丁吗？", "下载提示", "继续下载", "停止操作"))
                            {
                                DoPatchUpdate();
                            }
                        }
                        else if (GlobalValues.LocalVersion != GlobalValues.VersionList[GlobalValues.VersionList.Length - 2][1])
                        {
                            for (int i = 0; i < GlobalValues.VersionList.Length; i++)
                            {
                                if (GlobalValues.LocalVersion == GlobalValues.VersionList[GlobalValues.VersionList.Length - 1 - i][1])
                                {
                                    if (IMessageBox.Show("你的客户端版本过于老旧，需要下载多个更新补丁\n你需要下载" + i + "个补丁，是否继续？", "下载提示", "继续下载", "取消下载"))
                                    {
                                        if (File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile)) File.Delete(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile);
                                        DoPatchUpdate(i);
                                    }
                                    return;
                                }
                            }
                            if (IMessageBox.Show("游戏版本未知,无法进行补丁更新\n为确保游戏正常需下载完整的游戏本体，是否继续？", "下载提示", "继续下载", "稍后下载"))
                            {
                                DoMainInstall();
                            }
                        }
                        else
                        {
                            DoPatchUpdate();
                        }
                    }
                    break;
            }
        }
        private void DoGameWindowPositionReset(object o)
        {
            if (IMessageBox.Show("该操作会关闭游戏并将你的游戏窗口重置到屏幕左上角且无法撤销，是否继续操作", "游戏窗口重置", "确定", "取消"))
            {
                if (Process.GetProcessesByName(GlobalValues.GameExecuteFile).ToList().Count > 0)
                {
                    IFunc.CloseProc(GlobalValues.GameExecuteFile);
                }
                IFunc.WriteGameConfigFile("WindowPosition", "@Point(0 0)");
                GlobalValues.GameWindowW = "0";
                GlobalValues.GameWindowH = "0";
            }
        }
        private void DoSetGameDirectory(object o)
        {
            string flag = o.ToString();
            switch (flag)
            {
                case "Select":
                    {
                        FolderBrowserDialog fbd1 = new FolderBrowserDialog() { Description = "选择游戏目录", RootFolder = System.Environment.SpecialFolder.MyComputer };
                        if (fbd1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            ShowModel.GameDirectory = fbd1.SelectedPath;
                        }
                    }
                    break;
                case "Install":
                    {
                        FolderBrowserDialog fbd2 = new FolderBrowserDialog() { Description = "选择安装目录", RootFolder = System.Environment.SpecialFolder.MyComputer };
                        if (fbd2.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            ShowModel.GameDirectory = fbd2.SelectedPath + GlobalValues.InstallDir;
                        }
                    }
                    break;
            }
        }
        private void DoThemeChange(object o)
        {
            for (int i = 0; i < 8; i++) if (ShowModel.ThemeColorChose[i] == true) ShowModel.ThemeColorChose[i] = false;
            if (null != o)
            {
                if (o.ToString() == "Custom")
                {
                    System.Windows.Forms.ColorDialog colorDialog = new System.Windows.Forms.ColorDialog();
                    if (colorDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        o = ColorTranslator.ToHtml(colorDialog.Color);
                        GlobalValues.ThemeColor = o.ToString();
                    }
                    else DoSettingViewChange("SettingViewThemeSettingView");
                }
                else GlobalValues.ThemeColor = o.ToString();
            }
            switch (GlobalValues.ThemeColor)
            {
                case "#3D6CB4": ShowModel.ThemeColorChose[0] = true; break;
                case "#780000": ShowModel.ThemeColorChose[1] = true; break;
                case "#171717": ShowModel.ThemeColorChose[2] = true; break;
                case "#F3AAB1": ShowModel.ThemeColorChose[3] = true; break;
                case "#7E2065": ShowModel.ThemeColorChose[4] = true; break;
                case "#FEBA07": ShowModel.ThemeColorChose[5] = true; break;
                case "#006600": ShowModel.ThemeColorChose[6] = true; break;
                default: ShowModel.ThemeColorChose[7] = true; break;
            }

            try
            {
                System.Windows.Media.Color c = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString((GlobalValues.ThemeColor));
                ColorModel.ThemeColor = GlobalValues.ThemeColor;
                if (c.R == 61 && c.G == 108 && c.B == 180) { ColorModel.LightThemeColor = "#8797BF"; ColorModel.DarkThemeColor = "#131F2F"; ColorModel.ControlFontColor = "#FFF"; return; }
                ColorModel.LightThemeColor = System.Windows.Media.Color.FromRgb((byte)((c.R + 198) / 2), (byte)((c.G + 198) / 2), (byte)((c.B + 198) / 2)).ToString();
                ColorModel.DarkThemeColor = System.Windows.Media.Color.FromRgb((byte)((c.R + 200) / 4), (byte)((c.G + 200) / 4), (byte)((c.B + 200) / 4)).ToString();
                if ((c.R * 30 + c.G * 59 + c.B * 11 + 50) / 100 >= 160) { ColorModel.ControlFontColor = "#000"; }
                else { ColorModel.ControlFontColor = "#FFF"; }
            }
            catch { GlobalValues.ThemeColor = "#3D6CB4"; ShowModel.ThemeColorChose[7] = false; ShowModel.ThemeColorChose[1] = true; }
        }
        private void DoChangeLocalVersion(object o)
        {
            string temp = IInputBox.Show("请输入新的本地游戏版本", "更改本地游戏版本");
            if (!string.IsNullOrEmpty(temp))
            {
                GlobalValues.LocalVersion = temp;
                ShowModel.LocalVersion = temp;
                INIOperation.INIWriteValue(GlobalValues.GameDir + "\\version.ini", "Vup", "LocalVersion", temp);
            }
        }
        private void DoAutoCheckLauncherUpdate(object o)
        {
            if (ShowModel.LUBConent == "关闭启动器更新")
            {
                if (IMessageBox.Show("如果关闭，将再也无法获取启动器的更新\n失去启动器BUG的修复与功能的更新\n真的要关闭吗？", "重要通知", "坚持如此", "还是算了"))
                {
                    ShowModel.LUBConent = "打开启动器更新";
                    GlobalValues.AutoCheckLauncherUpdate = false;
                }
            }
            else
            {
                ShowModel.LUBConent = "关闭启动器更新";
                GlobalValues.AutoCheckLauncherUpdate = true;
            }
        }
        private async void InitContent()
        {
            IFunc.LoadConfigFile();
            IFunc.LoadGameConfigFile();

            DoViewChange("StartView");
            DoSettingViewChange("SettingViewGameSettingView");
            DoThemeChange(null);

            ShowModel.LocalVersion = GlobalValues.LocalVersion;
            ShowModel.NameInGame = GlobalValues.NameInGame;
            ShowModel.GameHostIP = GlobalValues.GameHostIP;
            ShowModel.GameDirectory = GlobalValues.GameDir;
            ShowModel.GameWindowW = GlobalValues.GameWindowW;
            ShowModel.GameWindowH = GlobalValues.GameWindowH;
            if (GlobalValues.CloseWhenStart) ShowModel.CloseWhenStart[0] = true;
            else ShowModel.CloseWhenStart[1] = true;
            if (GlobalValues.StartShowNotice) ShowModel.StartShowNotice[0] = true;
            else ShowModel.StartShowNotice[1] = true;
            if (GlobalValues.AutoCheckLauncherUpdate) ShowModel.LUBConent = "关闭启动器更新";
            else ShowModel.LUBConent = "打开启动器更新";

            await Task.Run(() =>
            {
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                IFunc.GetRefresh();
                ShowModel.LatestVersion = GlobalValues.LatestVersion;
                ShowModel.OfficialSite = GlobalValues.OfficialUrl;
            });
            await Task.Delay(500);
            if (GlobalValues.AutoCheckLauncherUpdate) IFunc.ShowLauncherUpdate();
            if (GlobalValues.FirstTimeStart)
            {
                if (IMessageBox.Show("欢迎来到Vup杀的世界！\n在这里，你可以从另一个角度体验虚拟主播带来的快乐\n用新梗给自己，给大家带来笑容吧！\n小伙伴们不要忘了点击下方按钮加入我们一起讨论哦！", "初次见面，观察者们！", "进入官网", "暂不需要"))
                    System.Diagnostics.Process.Start("https://" + GlobalValues.OfficialUrl.Replace("http://", string.Empty).Replace("https://", string.Empty));
                if (IMessageBox.Show("检测到你是第一次打开启动器\n是否安装游戏本体？\n没有游戏本体是无法进行游戏的\n游戏下载入口可在设置中找到", "游戏安装", "立即安装", "暂不需要"))
                    DoViewChange("GameInstallView");
            }
            else IFunc.ShowNotice();
        }
        private void RefreshContent(object sender, ElapsedEventArgs e)
        {
            ShowModel.LocalVersion = GlobalValues.LocalVersion;
            ShowModel.LatestVersion = GlobalValues.LatestVersion;
            GlobalValues.GameDir = ShowModel.GameDirectory;
            if (ShowModel.CloseWhenStart[0]) GlobalValues.CloseWhenStart = true;
            else GlobalValues.CloseWhenStart = false;
            if (ShowModel.StartShowNotice[0]) GlobalValues.StartShowNotice = true;
            else GlobalValues.StartShowNotice = false;
            if (GlobalValues.DebugMode) ShowModel.DebugModeTextVisibility = "Visible";
            else ShowModel.DebugModeTextVisibility = "Collapsed";

            IFunc.RefreshVersionState();
            switch (GlobalValues.VersionState)
            {
                case 0:
                    ShowModel.UpdateIconVisibility = "Collapsed";
                    ShowModel.AutoUpdateButtonContent = "无网络连接";
                    break;
                case 1:
                    ShowModel.UpdateIconVisibility = "Collapsed";
                    ShowModel.AutoUpdateButtonContent = "正在检测";
                    break;
                case 2:
                    ShowModel.UpdateIconVisibility = "Collapsed";
                    ShowModel.AutoUpdateButtonContent = "自动更新";
                    break;
                case 3:
                    ShowModel.UpdateIconVisibility = "Visible";
                    ShowModel.AutoUpdateButtonContent = "自动更新";
                    break;
                default:
                    ShowModel.UpdateIconVisibility = "Collapsed";
                    ShowModel.AutoUpdateButtonContent = "未知错误";
                    break;
            }
        }
        public void SaveConfigFile()
        {
            IFunc.WriteConfig("AutoCheckLauncherUpdate", GlobalValues.AutoCheckLauncherUpdate.ToString());
            IFunc.WriteConfig("CloseWhenStart", GlobalValues.CloseWhenStart.ToString());
            IFunc.WriteConfig("GameDirectory", GlobalValues.GameDir);
            IFunc.WriteConfig("StartShowNotice", GlobalValues.StartShowNotice.ToString());
            IFunc.WriteConfig("ThemeColor", GlobalValues.ThemeColor);
            IFunc.WriteConfig("ThemeColorTitle", GlobalValues.ThemeColorTitle);
        }

        public async void DoPatchUpdate(int count = 1)
        {
            if (IDownload.TaskName == "正在解压资源" || IDownload.TaskName == "任务完成") return;
            bool downloadsuccess = false;
            if (!File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.GameExecuteFile + ".exe") && !File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.GameExecuteFileVup + ".exe"))
            {
                if (IMessageBox.Show("请先下载游戏或设置游戏目录", "更新出错", "前往设置", "暂不需要", true))
                {
                    DoViewChange("SettingView");
                    DoSettingViewChange("SettingViewStartSettingView");
                }
                return;
            }
            else if (GlobalValues.LocalVersion == "未知版本")
            {
                if (IMessageBox.Show("无法检测您的游戏版本\n建议通过启动器方式获取游戏本体", "更新提示", "前往安装", "暂不需要", true))
                {
                    DoViewChange("SettingView");
                    DoSettingViewChange("SettingViewOtherSettingView");
                    return;
                }
            }
            if (File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile))
            {
                if (IMessageBox.Show("检测到上次未下载完的文件，是否继续上次更新？", "文件提示", "继续更新", "删除文件")) { }
                else
                {
                    File.Delete(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile);
                }
            }
            ShowModel.IsDownloadButtonShow = true;
            IDownload.TaskOK = false;
            await Task.Delay(200);
            IDownload.TaskViewVisiability = "Visiable";
            IDownload.MainViewVisiability = "Visiable";
            IDownload.TaskTitle = "游戏补丁自动更新";

            for (int i = 1; i <= count; i++)
            {
                if (count == 1)
                {
                    IDownload.TaskName = "正在下载资源";
                }
                else
                {
                    IDownload.TaskName = "共" + count + "个资源，正在下载第" + i + "个资源";
                }
                await Task.Run(() =>
                {
                    string url = GlobalValues.VersionList[GlobalValues.VersionList.Length - 1 - count + i][4];
                    if (IDownload.Start(url, GlobalValues.GameDir + "\\" + GlobalValues.PatchFile)) downloadsuccess = true;
                    else downloadsuccess = false;
                });

                if (downloadsuccess)
                {
                    IFunc.ReportPatchDownloadTimesPlus();
                    IDownload.TaskName = "资源下载完成";
                    await Task.Delay(500);
                    IDownload.TaskName = "文件校验中";
                    await Task.Delay(500);
                    string filemd5 = IFunc.GetFileMD5(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile);
                    string sourcemd5 = GlobalValues.VersionList[GlobalValues.VersionList.Length - 1 - count + i][5];
                    if (filemd5 != sourcemd5.ToUpper())
                    {
                        IMessageBox.Show("文件校验失败,请稍后再试", "校验失败", "好的");
                        if (File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile)) File.Delete(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile);
                        IDownload.TaskViewVisiability = "Collapsed";
                        IDownload.TaskTitle = "";
                        IDownload.TaskName = "";
                        IDownload.TaskOK = true;
                        if (IDownload.MainViewVisiability == "Collapsed") ShowModel.IsDownloadButtonShow = false;
                        return;
                    }
                    else
                    {
                        try
                        {
                            IDownload.TaskName = "正在解压文件";
                            await Task.Run(() => { IFunc.FileExtract(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile); });
                            GlobalValues.LocalVersion = GlobalValues.VersionList[GlobalValues.VersionList.Length - 1 - count + i][1];
                            INIOperation.INIWriteValue(GlobalValues.GameDir + "\\version.ini", "Vup", "LocalVersion", GlobalValues.LocalVersion);
                            IDownload.TaskName = "文件解压完成";
                        }
                        catch
                        {
                            IDownload.TaskName = "文件解压失败";
                            if (File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile)) File.Delete(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile);
                            if (Directory.Exists(GlobalValues.GameDir + @"\.temp")) Directory.Delete(GlobalValues.GameDir + @"\.temp", true);
                            IMessageBox.Show("无法解压至指定目录，但您仍可以尝试以下方案：\n1、关闭游戏后再进行更新\n2、重启系统后再进行更新\n3、以管理员权限打开启动器进行更新\n4、进入游戏目录选择”patch.zip“手动更新", "更新出错", "好的", null, true);
                            IDownload.TaskViewVisiability = "Collapsed";
                            IDownload.TaskTitle = "";
                            IDownload.TaskName = "";
                            IDownload.TaskOK = true;
                            if (IDownload.MainViewVisiability == "Collapsed") ShowModel.IsDownloadButtonShow = false;
                            return;
                        }
                    }
                }
            }

            await Task.Delay(500);
            IDownload.TaskName = "任务完成";
            if (File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile)) File.Delete(GlobalValues.GameDir + "\\" + GlobalValues.PatchFile);
            await Task.Delay(500);
            IDownload.TaskViewVisiability = "Collapsed";
            IDownload.TaskTitle = "";
            IDownload.TaskName = "";
            IDownload.TaskOK = true;
            if (IDownload.MainViewVisiability == "Collapsed") ShowModel.IsDownloadButtonShow = false;
        }
        public async void DoMainInstall()
        {
            if (IDownload.TaskName == "游戏主体文件下载完成" || IDownload.TaskName == "正在解压资源" || IDownload.TaskName == "任务完成") return;
            if (!GlobalValues.HaveNet) await Task.Run(INet.GetVersionCSV);
            bool downloadsuccess = false;
            ShowModel.IsDownloadButtonShow = true;
            IDownload.TaskTitle = "游戏主体文件安装";
            IDownload.TaskName = "正在下载游戏主体文件";
            IDownload.TaskOK = false;
            await Task.Delay(200);
            IDownload.TaskViewVisiability = "Visiable";
            IDownload.MainViewVisiability = "Visiable";
            await Task.Run(() =>
            {
                if (IDownload.Start(GlobalValues.VersionList[GlobalValues.VersionList.Length - 1][2], GlobalValues.GameDir + "\\" + GlobalValues.MainFile)) downloadsuccess = true;
                else downloadsuccess = false;
            });
            if (downloadsuccess)
            {
                IFunc.ReportMainDownloadTimesPlus();
                IDownload.TaskName = "游戏主体文件下载完成";
                await Task.Delay(500);
                IDownload.TaskName = "文件校验中";
                string filemd5 = IFunc.GetFileMD5(GlobalValues.GameDir + "\\" + GlobalValues.MainFile);
                string sourcemd5 = GlobalValues.VersionList[GlobalValues.VersionList.Length - 1][3];
                if (filemd5 != sourcemd5.ToUpper())
                {
                    IMessageBox.Show("文件校验失败,请稍后再试", "校验失败", "好的");
                    if (File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.MainFile)) File.Delete(GlobalValues.GameDir + "\\" + GlobalValues.MainFile);
                    IDownload.TaskViewVisiability = "Collapsed";
                    IDownload.TaskTitle = "";
                    IDownload.TaskName = "";
                    IDownload.TaskOK = true;
                    if (IDownload.MainViewVisiability == "Collapsed") ShowModel.IsDownloadButtonShow = false;
                    return;
                }
                IDownload.TaskName = "正在解压资源";
                await Task.Run(() => IFunc.FileExtract(GlobalValues.GameDir + "\\" + GlobalValues.MainFile));
                IDownload.TaskName = "任务完成";
                if (File.Exists(GlobalValues.GameDir + "\\" + GlobalValues.MainFile)) File.Delete(GlobalValues.GameDir + "\\" + GlobalValues.MainFile);
                await Task.Delay(500);
                IDownload.TaskViewVisiability = "Collapsed";
                IDownload.TaskTitle = "";
                IDownload.TaskName = "";
                IDownload.TaskOK = true;
                if (IDownload.MainViewVisiability == "Collapsed") ShowModel.IsDownloadButtonShow = false;
                IFunc.LoadGameConfigFile();
            }
        }
    }
}